<template>
    <div class="map-wrapper">
      <div id="map-container" style="width: 100%; height: 80vh"></div>
      <div v-if="currentSpot" class="spot-selector" :class="{ expanded: isExpanded }">
        <!-- 左侧景点栏保持不变 -->
      </div>
      <!-- 修改为浮动式详情面板 -->
      <div v-if="selectedSpot" class="spot-details" :style="detailPosition">
        <div class="details-content">
          <h2>{{ selectedSpot.name }}</h2>
          <img v-if="selectedSpot.details?.image" :src="selectedSpot.details.image" alt="景点图片" />
          <p v-if="selectedSpot.details?.description">{{ selectedSpot.details.description }}</p>
          <p v-else>暂无详情描述</p>
          <button class="close-btn" @click="selectedSpot = null">×</button>
        </div>
      </div>
    </div>
  </template>
  
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { loadAMap } from '@/utils/amapLoader'
  import { scenicSpots } from '@/mock/scenicSpots'
  
  //响应式变量
  const isExpanded = ref(false)
  const map = ref(null) // 将地图实例存储为响应式变量
  const currentSpot = ref(null)
  const route = useRoute()
  const selectedSpot = ref(null)
  const detailPosition = ref({
    top: 'auto',
    bottom: 'auto',
    left: 'auto',
    right: 'auto'
  })
  const highlightedMarker = ref(null) //存储当前高亮标记
  
  //函数
  const toggleExpand = () => {
    isExpanded.value = !isExpanded.value
  }
  
  const focusOnSpot = (subSpot) => {
    if (!map.value) {
      console.error('地图实例未初始化')
      return
    }
    // 清除之前的高亮
    if (highlightedMarker.value) {
      resetMarkerStyle(highlightedMarker.value)
      highlightedMarker.value = null
    }
    // 移动到子景点位置并高亮
    const [lng, lat] = virtualToReal(subSpot.x, subSpot.y)
    console.log('移动至坐标:', lng, lat) // 调试用
    map.value.panTo([lng, lat]) // 平滑移动到目标位置
    map.value.setZoom(30, false) // 缓慢放大，不使用动画
    // 高亮当前标记
    const markers = map.value.getAllOverlays('marker')
    markers.forEach(m => {
      const pos = m.getPosition()
      if (pos.lng === lng && pos.lat === lat) {
        // 使用金色高亮效果，不同于主景点的红色
        m.setContent(createMarkerContent(subSpot, true))
        highlightedMarker.value = m
      }
    })
  
    // 设置详情面板位置
    setDetailPosition(lng, lat)
  }
  
  // 新增：创建标记内容的函数
  const createMarkerContent = (spot, isHighlighted = false) => {
    const isMainSpot = !spot.id // 假设主景点没有id属性
    const markerSize = isMainSpot ? 16 : 14
    const markerColor = isHighlighted ? '#FFD700' : (isMainSpot ? '#FF3333' : '#3388FF')
    const fontSize = isMainSpot ? 14 : 12
    
    return `
      <div style="display:flex; flex-direction:column; align-items:center;">
        <div style="
          width:${markerSize}px; 
          height:${markerSize}px; 
          background:${markerColor};
          border-radius:50%;
          display:flex;
          justify-content:center;
          align-items:center;
          color:#FFFFFF;
          font-size:${fontSize}px;
          font-weight:bold;
          border:2px solid white;
          box-shadow:0 2px 4px rgba(0,0,0,0.3);
          ${isHighlighted ? 'transform: scale(1.3); transition: transform 0.3s;' : ''}
        "></div>
        <div style="
          margin-top:8px;
          padding:2px 8px;
          background:white;
          color:#333;
          font-size:${fontSize}px;
          font-weight:bold;
          border-radius:4px;
          box-shadow:0 1px 2px rgba(0,0,0,0.2);
        ">${spot.name}</div>
      </div>
    `
  }
  
  // 新增：重置标记样式
  const resetMarkerStyle = (marker) => {
    const pos = marker.getPosition()
    const realPos = [pos.lng, pos.lat]
    const spot = findSpotByPosition(realPos)
    if (spot) {
      marker.setContent(createMarkerContent(spot))
    }
  }
  
  // 新增：根据位置查找景点
  const findSpotByPosition = ([lng, lat]) => {
    if (!currentSpot.value) return null
    
    // 检查主景点
    const mainSpotPos = virtualToReal(currentSpot.value.center.x, currentSpot.value.center.y)
    if (Math.abs(mainSpotPos[0] - lng) < 0.0001 && Math.abs(mainSpotPos[1] - lat) < 0.0001) {
      return { ...currentSpot.value.center, name: currentSpot.value.name }
    }
    
    // 检查子景点
    return currentSpot.value.subSpots.find(sub => {
      const subPos = virtualToReal(sub.x, sub.y)
      return Math.abs(subPos[0] - lng) < 0.0001 && Math.abs(subPos[1] - lat) < 0.0001
    })
  }
  
  // 根据点击位置设置详情面板位置
  const setDetailPosition = (lng, lat) => {
    // 获取地图容器尺寸
    const container = document.getElementById('map-container')
    const rect = container.getBoundingClientRect()
    
    // 将经纬度转换为屏幕坐标
    const pixel = map.value.lngLatToContainer([lng, lat])
    
    // 计算最佳显示位置
    const position = { top: 'auto', bottom: 'auto', left: 'auto', right: 'auto' }
    
    if (pixel.y < rect.height / 2) {
      position.top = `${pixel.y + 20}px`  // 如果在上面半区，详情显示在下方
    } else {
      position.bottom = `${rect.height - pixel.y + 20}px`  // 如果在下面半区，详情显示在上方
    }
    
    if (pixel.x < rect.width / 2) {
      position.left = `${pixel.x + 20}px`  // 如果在左半区，详情显示在右侧
    } else {
      position.right = `${rect.width - pixel.x + 20}px`  // 如果在右半区，详情显示在左侧
    }
    
    detailPosition.value = position
  }
  
  
  function showDetails(spot) {
    selectedSpot.value = spot
  }
  
  // 虚拟坐标范围定义
  const VIRTUAL_RANGE = {
    minX: 0,
    maxX: 1000,
    minY: 0,
    maxY: 1000
  };
  
  // 实际映射到的地理范围（北京某区域）
  const REAL_BOUNDS = {
    minLng: 116.397,  // 最小经度
    maxLng: 116.405,  // 最大经度
    minLat: 39.915,   // 最小纬度
    maxLat: 39.920    // 最大纬度
  };
  
  // 坐标转换函数
  function virtualToReal(x, y) {
    const lng = REAL_BOUNDS.minLng + 
      (x - VIRTUAL_RANGE.minX) * (REAL_BOUNDS.maxLng - REAL_BOUNDS.minLng) / 
      (VIRTUAL_RANGE.maxX - VIRTUAL_RANGE.minX);
    
    const lat = REAL_BOUNDS.maxLat - 
      (y - VIRTUAL_RANGE.minY) * (REAL_BOUNDS.maxLat - REAL_BOUNDS.minLat) / 
      (VIRTUAL_RANGE.maxY - VIRTUAL_RANGE.minY);
    
    return [lng, lat];
  }
  
  
  
  // 路由参数
  
  const spotId = route.query.id // 从路由中获取景点 ID
  
  
  
  
  onMounted(async () => {
    try {
      // 获取当前景点数据
      const spotData = scenicSpots[spotId]
      if (!spotData) {
        console.error('未找到对应的景点数据')
        return
      }
      currentSpot.value = spotData
  
      // 加载高德地图 SDK
      const AMap = await loadAMap()
  
      // 初始化地图
      map.value = new AMap.Map('map-container', {
        zoom: 17,
        center: virtualToReal(spotData.center.x, spotData.center.y),
        viewMode: '2D',
        showIndoorMap: false,
        zoomEnable: true,
        dragEnable: true,
        rotateEnable: false,
        pitchEnable: false,
        layers: [],  // 不加载任何图层
        mapStyle: 'amap://styles/normal',  // 使用普通样式
        features: []  // 不显示任何要素
      })
  
      // 添加主景点标记
      const mainMarker = new AMap.Marker({
        position: virtualToReal(spotData.center.x, spotData.center.y),
        content: createMarkerContent({ 
          ...spotData.center, 
          name: spotData.name 
        }),
        offset: new AMap.Pixel(-15, -15) // 调整主景点偏移量
      })
      map.value.add(mainMarker)
  
      // 添加子景点标记
      spotData.subSpots.forEach((subSpot) => {
        const subMarker = new AMap.Marker({
          position: virtualToReal(subSpot.x, subSpot.y),
          content: createMarkerContent(subSpot),
          offset: new AMap.Pixel(-14, -10) // 使用统一尺寸计算
        })
  
        subMarker.on('click', () => {
          selectedSpot.value = subSpot
          focusOnSpot(subSpot)
        })
  
        map.value.add(subMarker)
      })
  
      // 增强版边线绘制
      spotData.edges.forEach((edge) => {
        const fromSpot = spotData.subSpots.find(s => s.id === edge.from)
        const toSpot = spotData.subSpots.find(s => s.id === edge.to)
  
        if (fromSpot && toSpot) {
          const lineStyle = {
            main: { color: '#CC0000', weight: 5, dash: false }, // 中轴线用粗红线
            side: { color: '#3388FF', weight: 3, dash: false }, // 东西六宫用蓝线
            path: { color: '#666666', weight: 2, dash: true } // 路径用灰色虚线
          }
  
          const style = lineStyle[edge.type] || lineStyle.side
  
          const line = new AMap.Polyline({
            path: [
              virtualToReal(fromSpot.x, fromSpot.y),
              virtualToReal(toSpot.x, toSpot.y)
            ],
            strokeColor: style.color,
            strokeWeight: style.weight,
            strokeOpacity: 0.8,
            strokeStyle: style.dash ? 'dashed' : 'solid',
            lineJoin: 'round'
          })
  
          map.value.add(line)
  
          // 为中轴线添加箭头标记
          if (edge.type === 'main') {
            const arrow = new AMap.Marker({
              position: virtualToReal(
                (fromSpot.x + toSpot.x) / 2,
                (fromSpot.y + toSpot.y) / 2
              ),
              content: `<div style="color:${style.color};font-size:16px">→</div>`,
              offset: new AMap.Pixel(-8, -8)
            })
            map.value.add(arrow)
          }
        }
      })
  
      // 调整视图以显示所有点
      map.value.setFitView()
    } catch (error) {
      console.error('加载高德地图失败:', error)
    }
  })
  </script>
  
  <style scoped>
  /* 增强地图容器样式 */
  .map-wrapper {
    position: relative;
    width: 100%;
    height: 80vh;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
  
  .spot-selector {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 999;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
    overflow: hidden;
    width: 200px;
    transition: all 0.3s ease;
  }
  .main-spot {
    padding: 12px 15px;
    font-weight: bold;
    color: #333;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;
  }
  
  .main-spot:hover {
    background: #f5f5f5;
  }
  
  .arrow {
    font-size: 12px;
    transition: transform 0.3s;
  }
  
  .arrow.rotated {
    transform: rotate(180deg);
  }
  
  .sub-spots-wrapper {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease;
  }
  
  .spot-selector.expanded .sub-spots-wrapper {
    max-height: 400px; /* 根据实际内容调整 */
    overflow-y: auto;
  }
  
  .sub-spot {
    padding: 10px 15px;
    color: #555;
    cursor: pointer;
    transition: all 0.2s;
  }
  
  .sub-spot:hover {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  .sub-spot:not(:last-child) {
    border-bottom: 1px solid #f0f0f0;
  }
  
  .spot-details {
    position: absolute;
    z-index: 999;
    max-width: 300px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    backdrop-filter: blur(5px);
    border: 1px solid rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
  }
  
  .details-content {
    padding: 15px;
    position: relative;
  }
  
  .details-content h2 {
    margin: 0 0 10px 0;
    font-size: 18px;
    color: #333;
  }
  
  .details-content img {
    width: 100%;
    max-height: 150px;
    object-fit: cover;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  
  .details-content p {
    margin: 0;
    font-size: 14px;
    color: #666;
    line-height: 1.5;
  }
  
  .close-btn {
    position: absolute;
    top: 5px;
    right: 5px;
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    color: #999;
    padding: 0 5px;
  }
  
  .close-btn:hover {
    color: #333;
  }
  </style>